package net.kehuilai.tools;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by genghz on 16/12/22.
 */
public class ServletTool {

    // 获取客户端的 ip
    public static String getClientRealIp(HttpServletRequest request) {
        String ip = null;

        if (request != null) {
            ip = request.getHeader("X-Forwarded-For");
            if (ip == null) ip = request.getHeader("X-Real-IP");
            if (ip == null) ip = request.getRemoteAddr();
        }

        if (ip != null && ip.contains(",")) {
            String[] ipList = ip.split(",");
            ip = ipList[0];
        }

        return ip == null ? "" : ip;
    }

    // 判断是否在微信环境下
    public static boolean isWxClient(HttpServletRequest request) {
        String agent = request.getHeader("User-Agent");
        agent = agent == null ? "" : agent.toLowerCase();
        return agent.contains("micromessenger");
    }

    // 获取完整的url
    public static String getClientUrl(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();

        sb.append(request.getRequestURL());

        String queryString = request.getQueryString();
        if (queryString == null || queryString.equals("")) {
            sb.append("?");
            sb.append(queryString);
        }

        return sb.toString();
    }
}
